package com.buding.fx.validators;

import cn.hutool.core.collection.CollectionUtil;
import com.jfoenix.validation.base.ValidatorBase;

import java.util.List;
import java.util.regex.Pattern;

public class ExcelImportValidator extends ValidatorBase {
    private int length;
    private static final Pattern FIELD_NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]*");
    private List<Object> rows;

    public ExcelImportValidator(int length,List<Object> rows){
        this.length = length;
        this.rows = rows;
    }
    @Override
    protected void eval() {
        if (CollectionUtil.isEmpty(rows)){
            setMessage("导入的excel文件第一行不能为空");
            hasErrors.set(true);
        }else{
            for (Object row : rows) {
                if (row.toString().length() > length - 1){
                    setMessage("excel文件列名: "+row+"长度不合法");
                    hasErrors.set(true);
                }else{
                    boolean result = FIELD_NAME_PATTERN.matcher(row.toString()).matches();
                    if (!result){
                        setMessage("excel文件列名: "+row+"不合法");
                    }
                    hasErrors.set(!result);
                }
            }
        }
    }
}
